package com.taoyibao.hongcanting.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.taoyibao.hongcanting.ui.HongApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;

/**
 * @author TangAnna
 * @description: File有关的工具类
 * @date :${DATA} 16:41
 */
public class FileUtils {
    private static final String TAG = "FileUtils";

    /**
     * 文件类型
     */
    public static final String FILE_TYPE_VIDEO = "video";//视频
    public static final String FILE_TYPE_IMG = "img";//图片
    public static final String FILE_TYPE_TEXT = "text";//文件
    //存放临时文件的目录
    public static final String TEMP = File.separator + AppUtils.getPackageName() + File.separator + "picture" + File.separator + "temp" + File.separator;
    /**
     * 安装包存放的路径
     */
    public static final String PACKAGE = File.separator + AppUtils.getPackageName() + File.separator + "package" + File.separator;


    /**
     * 应用文件的根地址
     */
    public static String mRootPath = getSDcardDir() + AppUtils.getPackageName();


    /**
     * 获取应用包名的文件夹下已占用了多少内存
     *
     * @return
     */
    public static long getAppUsedSpace() {
        File file = new File(mRootPath);
        long usableSpace = file.getUsableSpace();
        return usableSpace;
    }


    /**
     * 将Uri转成File
     *
     * @param uri
     * @return
     */
    public static File Uri2File(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    LogUtils.dNormal("Uri2File", "temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();
            return new File(path);
        } else {
            LogUtils.dNormal("Uri2File", "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }


    /**
     * 读取assets文件中的内容
     *
     * @param name 文件名称
     * @return
     */
    public static String readAssetsFile(String name) {
        try {
            AssetManager assets = HongApplication.getContext().getAssets();
            InputStream is = assets.open(name);
            InputStreamReader inputStream = new InputStreamReader(is);
            BufferedReader bufReader = new BufferedReader(inputStream);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            //关闭资源
            is.close();
            inputStream.close();
            bufReader.close();
            return Result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取sdcard的路径
     *
     * @return
     */
    public static String getSDcardDir() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            size = fis.available();
        } else {
            LogUtils.dNormal(TAG, "要获取大小的文件并不存在！");
        }
        return size;
    }

    /**
     * 删除SD卡中文件夹以及下面的所有文件  迭代
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }


    /**
     * 获取临时文件
     *
     * @return
     */
    public static File getTempFile() {
        return new File(Environment.getExternalStorageDirectory(), TEMP);
    }

    /**
     * 删除临时文件
     */
    public static void deleteTempFile() {
        deleteFile(getTempFile());
    }

    /**
     * 获取缓存大小
     *
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize() {
        try {
            long cacheSize = getFolderSize(HongApplication.getContext().getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                cacheSize += getFolderSize(HongApplication.getContext().getExternalCacheDir());
            }
            return getFormatSize(cacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "0K";
    }

    /**
     * 清除缓存
     */
    public static void clearAllCache() {
        deleteFile(HongApplication.getContext().getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteFile(HongApplication.getContext().getExternalCacheDir());
        }
    }

    // 获取文件大小
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }


    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "K";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "M";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


}
